﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.IO;
using Frame.Lib.Common;

namespace Frame.Web.Common
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class Upload : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            

            if (context.Request.InputStream.Length == 0)
            {
                return;
            }

            string fileName = context.Request.QueryString["filename"];
            int blockindex = int.Parse(context.Request.QueryString["blockindex"]);
            int blockcount = int.Parse(context.Request.QueryString["blockcount"]);

         
            string path = AppSetting.ShareFilePath + fileName;
            string tmpPath = path + ".tmp";//上传的临时文件

            FileStream fs = null;
            if (blockindex == 1)
            {
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
                if (!Directory.Exists(AppSetting.ShareFilePath))
                {
                    Directory.CreateDirectory(AppSetting.ShareFilePath);
                }
                fs = new FileStream(tmpPath, FileMode.Create, FileAccess.Write);

            }
            else
            {
                fs = new FileStream(tmpPath, FileMode.Append, FileAccess.Write);
            }


            byte[] buffer = new byte[10240];
            int readcount = context.Request.InputStream.Read(buffer, 0, buffer.Length);
            while (readcount > 0)
            {
                fs.Write(buffer, 0, readcount);
                readcount = context.Request.InputStream.Read(buffer, 0, buffer.Length);
            }
            fs.Flush();
            fs.Close();

            if (blockindex == blockcount)
            {
                File.Move(tmpPath, path);
            }

            context.Response.ContentType = "text/plain";
            context.Response.Write(blockindex);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
